package com.ze.familydayverpm.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.ui.f;

import com.ze.commontool.DisplayUtil;
import com.ze.commontool.LoadImageMgr;
import com.ze.commontool.NetHelper;
import com.ze.commontool.PublicInfo;
import com.ze.commontool.LoadImageMgr.ImageCallBack;
import com.ze.commontool.SoundPlayStop;
import com.ze.commontool.StringTools;
import com.ze.familyday.familyphotoframe.PhotoFrameActivity;
import com.ze.familyday.familyphotoframe.R;
import com.ze.model.PhotoModel.PicInfo;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat.Action;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class PicFragment extends RelativeLayout  implements RelativeLayoutImp {
	
	private 	Context mContext;
	private static final float FULL_RATE = 10f/9f;
	/**
	 * copy from mouse 
	 */
	//多图排版
	public final static int [] picLayoutid = new int[]{R.layout.pic_one, R.layout.pic_two
		,R.layout.pic_three, R.layout.pic_four, R.layout.pic_five, R.layout.pic_six
		,R.layout.pic_seven, R.layout.pic_eight, R.layout.pic_nine};
	public final static int [] imgid = new int[]{R.id.img1, R.id.img2, R.id.img3, 
		R.id.img4, R.id.img5, R.id.img6, R.id.img7, R.id.img8, R.id.img9};
	public View picView;
	public ImageView [] img = new ImageView[9];
	private int [] levelId = new int []{R.drawable.level_0, R.drawable.level_1, R.drawable.level_2,
			R.drawable.level_3, R.drawable.level_4, R.drawable.level_5, R.drawable.level_6,
			R.drawable.level_7, R.drawable.level_8, R.drawable.level_9,};
	
	/**
	 * 字体处理
	 */
	TextPaint newPaint_name, newPaint_time, newPaint_say, newPaint_saybody;
	/**
	 * 各字体View
	 */
	TextView new_name_back, new_name, new_time_back, new_time, new_say_back,
				new_say;
	
	/**
	 * 数据
	 */
//	private List<JSONObject> mListJSON;
	private 	JSONObject mObject;
	public static final String 	IMG_DETAIL_TAIL = "!580";
	public static final int 		ONCE_GET = 5;
	boolean isLandscape = false;
	
	public PicFragment(Context context) {
		// TODO Auto-generated constructor stub
		super(context);
		mContext = context;
//		setupViews();
	}
	 public PicFragment(Context context, AttributeSet attrs) {  
	        super(context, attrs);  
	        setupViews();  
	    } 
	//初始化View
    public void setupViews(){  
    }  
    public void pageDown()
    {
    }
    public void pageUp()
    {
    }
    private float touchY;
    /** 
     * 填充数据，共外部调用. 
     * @param object 
     */  
    public static int picNum = 1;
    public void setData(JSONObject object){ 
        this.mObject = object; 
//        ArrayList<PicInfo> 	imgArray = null;
        int picnum = 0;
        if ( this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE )
		{
			isLandscape = true;
		}else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
		{
			isLandscape = false;
		}
        
        if( !object.isNull("imgarray"))
		{
        	
        try {
			ArrayList<PicInfo> imgArray = (ArrayList<PicInfo>) object.get("imgarray");
			String imgUrl ;
			
			picNum = imgArray.size();
			
			if (picNum == 1) {
				int img_w = imgArray.get(0).width;
          		int img_h  = imgArray.get(0).height;
          		if ( ((double)img_h) / ((double)img_w) < FULL_RATE ){
          			if( isLandscape )
          			{
          				picView = LayoutInflater.from(mContext).inflate(R.layout.pic_one, null);
          			}else
          			{
          				picView = LayoutInflater.from(mContext).inflate(R.layout.pic_one_top, null);
          			}
          			
					new_name_back = (TextView) picView.findViewById(R.id.new_desc_name_back);
					new_name = (TextView) picView.findViewById(R.id.new_desc_name);
					new_time_back = (TextView) picView.findViewById(R.id.new_desc_time_back);
					new_time = (TextView) picView.findViewById(R.id.new_desc_time);
					new_say_back = (TextView) picView.findViewById(R.id.new_desc_back);
					new_say = (TextView) picView.findViewById(R.id.new_desc);
					if (isLandscape){
						//用户名
						new_name.setTextColor(Color.WHITE);
						newPaint_name = new_name_back.getPaint();
						newPaint_name.setStrokeWidth(1.0f);
						newPaint_name.setStyle(Style.STROKE);
						//时间
						new_time.setTextColor(Color.WHITE);
						newPaint_time = new_time_back.getPaint();
						newPaint_time.setStrokeWidth(1.0f);
						newPaint_time.setStyle(Style.STROKE);
						//图片内容
						new_say.setTextColor(Color.WHITE);
						newPaint_say = new_say_back.getPaint();
						newPaint_say.setStrokeWidth(1.0f);
						newPaint_say.setStyle(Style.STROKE);
					}else {
						//用户名
						new_name_back.setTextColor(getResources().getColor(R.color.picinfo_name));
						new_name.setTextColor(getResources().getColor(R.color.picinfo_name));
						newPaint_name = new_name_back.getPaint();
						newPaint_name.setStrokeWidth(0.0f);
						newPaint_name.setStyle(Style.STROKE);
						//时间
						new_time_back.setTextColor(getResources().getColor(R.color.picinfo_time));
						new_time.setTextColor(getResources().getColor(R.color.picinfo_time));
						newPaint_time = new_time_back.getPaint();
						newPaint_time.setStrokeWidth(0.0f);
						newPaint_time.setStyle(Style.STROKE);
						//图片内容
						newPaint_say = new_say_back.getPaint();
						newPaint_say.setStrokeWidth(0.0f);
						newPaint_say.setStyle(Style.STROKE);
					}
          			
          			
          		} 
          		else {
          			int random = (int) (Math.random()*10);
          			if (random % 2 == 0) 
          				picView = LayoutInflater.from(mContext).inflate(R.layout.pic_one_left, null);
          			else
          				picView = LayoutInflater.from(mContext).inflate(R.layout.pic_one_right, null);
          			
					new_name_back = (TextView) picView.findViewById(R.id.new_desc_name_back);
					new_name = (TextView) picView.findViewById(R.id.new_desc_name);
					new_time_back = (TextView) picView.findViewById(R.id.new_desc_time_back);
					new_time = (TextView) picView.findViewById(R.id.new_desc_time);
					new_say_back = (TextView) picView.findViewById(R.id.new_desc_back);
					new_say = (TextView) picView.findViewById(R.id.new_desc);
					if (isLandscape) {
						//用户名
						new_name_back.setTextColor(getResources().getColor(R.color.picinfo_name));
						new_name.setTextColor(getResources().getColor(R.color.picinfo_name));
						newPaint_name = new_name_back.getPaint();
						newPaint_name.setStrokeWidth(0.0f);
						newPaint_name.setStyle(Style.STROKE);
						//时间
						new_time_back.setTextColor(getResources().getColor(R.color.picinfo_time));
						new_time.setTextColor(getResources().getColor(R.color.picinfo_time));
						newPaint_time = new_time_back.getPaint();
						newPaint_time.setStrokeWidth(0.0f);
						newPaint_time.setStyle(Style.STROKE);
						//图片内容
						newPaint_say = new_say_back.getPaint();
						newPaint_say.setStrokeWidth(0.0f);
						newPaint_say.setStyle(Style.STROKE);
					} else {
						new_name.setTextColor(Color.WHITE);
						newPaint_name = new_name_back.getPaint();
						newPaint_name.setStrokeWidth(1.0f);
						newPaint_name.setStyle(Style.STROKE);
						new_time.setTextColor(Color.WHITE);
						newPaint_time = new_time_back.getPaint();
						newPaint_time.setStrokeWidth(1.0f);
						newPaint_time.setStyle(Style.STROKE);
						new_say.setTextColor(Color.WHITE);
						newPaint_say = new_say_back.getPaint();
						newPaint_say.setStrokeWidth(1.0f);
						newPaint_say.setStyle(Style.STROKE);
					}
          		}
          		img[0] = (ImageView) picView.findViewById(R.id.img1);
			} 
			else{
				picView = LayoutInflater.from(mContext).inflate(picLayoutid[picNum - 1], null);
				for (int i = 0; i < picNum; i ++)
					img[i] = (ImageView) picView.findViewById(imgid[i]);
					//img_1 = (ImageView) view.findViewById(R.id.img1);
				//用户名
				new_name_back = (TextView) picView.findViewById(R.id.new_desc_name_back);
				new_name = (TextView) picView.findViewById(R.id.new_desc_name);
				new_name_back.setTextColor(getResources().getColor(R.color.picinfo_name));
				new_name.setTextColor(getResources().getColor(R.color.picinfo_name));
				newPaint_name = new_name_back.getPaint();
				newPaint_name.setStrokeWidth(0.0f);
				newPaint_name.setStyle(Style.STROKE);
				//时间
				new_time_back = (TextView) picView.findViewById(R.id.new_desc_time_back);
				new_time = (TextView) picView.findViewById(R.id.new_desc_time);
				new_time_back.setTextColor(getResources().getColor(R.color.picinfo_time));
				new_time.setTextColor(getResources().getColor(R.color.picinfo_time));
				newPaint_time = new_time_back.getPaint();
				newPaint_time.setStrokeWidth(0.0f);
				newPaint_time.setStyle(Style.STROKE);
				//图片内容
				new_say_back = (TextView) picView.findViewById(R.id.new_desc_back);
				new_say = (TextView) picView.findViewById(R.id.new_desc);
				newPaint_say = new_say_back.getPaint();
				newPaint_say.setStrokeWidth(0.0f);
				newPaint_say.setStyle(Style.STROKE);
					
			}
//			photoFrameView.removeAllViews();
			picView.setOnClickListener(ButtonOnclickListener);
			picView.setOnTouchListener(ontouchlistener);
			addView(picView);
//			photoFrameView.addView(picView, new LayoutParams(LayoutParams.FILL_PARENT, 
//					LayoutParams.FILL_PARENT));
			
			//Log.v("mouse", "帖子的图片数:" + imgArray.size());
          	for (int i = 0; i < imgArray.size(); i++) {
          		if ( i == 2 ) {
          			// 电子相框版本。只有一张，其他的不加入
					//break;
				}
          		imgUrl = imgArray.get(i).url;
          		
          		/**
          		 * 注释掉代码 
          		 * By mouse 2013.10.30PM
          		 */
          		int endFlag = -1;
          		int img_w = imgArray.get(i).width;
          		int img_h  = imgArray.get(i).height;
          		endFlag = imgUrl.indexOf("!");
          		if ( endFlag != -1 || imgUrl.contains(PublicInfo.picID_default_head) )
          		{
          			if( ! imgUrl.contains(PublicInfo.picID_default_head))
          			{
          				imgUrl = imgUrl.substring(0, endFlag);
						if( ((float)img_h) / ((float)img_w) < FULL_RATE )
						{
							imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_LARGE;
						}else
						{
							imgUrl = imgUrl + PublicInfo.PHOTO_SIZE_HALF;
						}
          			}
					
          		}
          		
          		//img_1.setVisibility(View.VISIBLE);
          		
          		Drawable imageDrawable = null;
      			if( imgUrl.contains(PublicInfo.picID_default_head))
      			{
      				if (imgUrl.equals(PublicInfo.picID_defaults[0])) {
      					imageDrawable = getResources().getDrawable(R.drawable.default_1);
					}else  if (imgUrl.equals(PublicInfo.picID_defaults[1]))
					{
						imageDrawable = getResources().getDrawable(R.drawable.default_2);
					}else  if (imgUrl.equals(PublicInfo.picID_defaults[2]))
					{
						imageDrawable = getResources().getDrawable(R.drawable.default_3);
					}else 
					{
						imageDrawable = getResources().getDrawable(R.drawable.default_4);
					}
      			}else
      			{
      				//By mouse
      				
      				 imageDrawable = LoadImageMgr.getInstance().loadDrawble(imgUrl, 
 	      					img[i], 
 	              			imageCallBack);
      				
      			}
      			img[i].setImageDrawable(imageDrawable);
          	}//end for
          	setPicInfo(object);
        } catch (Exception e) {
			// TODO: handle exception
		}
		}
          
    }
    public void setPicInfo(JSONObject object)
	{
		if( object == null )
		{
			//say.setText("");
			//layout_info_say_back.setText("");
			//layout_info_name.setText("");
			if (new_name_back!=null)
				new_name_back.setText("");
			if (new_name != null)
				new_name.setText("");
			if (new_say_back != null)
				new_say_back.setText("");
			if (new_say != null)
				new_say.setText("");
			if (new_time_back != null)
				new_time_back.setText("");
			if (new_time != null)
				new_time.setText("");
			
			//layout_info_time.setText("");
			//layout_info_name_back.setText("");
			//layout_info_time_back.setText("");
			//layout_info.setVisibility(View.INVISIBLE);
		}else
		{
			//layout_info.setVisibility(View.VISIBLE);
			try {
				String str_say = object.optString("say","无标题");
				if (str_say.equals("")) {
					str_say = "无标题";
				}
				new_say_back.setText(str_say);//say.setText( str_say);
				new_say.setText(str_say);//layout_info_say_back.setText( str_say );
				//layout_info_name_back.setText(object.getString("name"));
				//layout_info_name.setText(object.getString("name"));
				new_name_back.setText(object.getString("name"));
				new_name.setText(object.getString("name"));
				
				if(object.getString("id").contains(PublicInfo.picID_default_head))
				{
					new_time.setText("");//layout_info_time.setText("");
					new_time_back.setText("");//layout_info_time_back.setText( "");
				}else
				{
					/*layout_info_time*/new_time.setText(NetHelper.transTime(Long.parseLong(object.getString("time"))) );
					/*layout_info_time_back*/new_time_back.setText( NetHelper.transTime(Long.parseLong(object.getString("time"))) );
				}
				
				
				
			} catch (Exception e) {
				// TODO: handle exception
			}
			
		}
		
	}
    public boolean isTextCut(TextView tv, String string)
    {
    	Paint paint  = tv.getPaint(); 
        paint.setTextSize(tv.getTextSize());
        // px = dp * (dpi / 160)
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
        int avail = PublicInfo.SCREEN_W - DisplayUtil.dip2px((40 + 18 + 10), dm.density);
    	String changeString = 
    		TextUtils.ellipsize(string, (TextPaint) paint, avail, TextUtils.TruncateAt.END).toString();
    	if (string.length() > changeString.length() ) {
			return true;
		}
    	return false;
    }
    /** 
     * 这里内存回收.外部调用. 
     */  
    
public ImageCallBack imageCallBack = new ImageCallBack() {
		
		@Override
		public void setImage(Drawable d, String url, ImageView view) {
			// TODO Auto-generated method stub
			if( /*mActiveImages.contains(view) &&*/ url.equals((String)view.getTag()))
			{
				view.setImageDrawable(d);
			}
		}
	};
    public void recycle(){  
//        mAlbumImageView.setImageBitmap(null);  
//        if ((this.mBitmap == null) || (this.mBitmap.isRecycled()))  
//            return;  
//        this.mBitmap.recycle();  
//        this.mBitmap = null;  
    }  
    /** 
     * 重新加载.外部调用. 
     */  
    public void reload(){  
//        try {  
//            int resId = mObject.getInt("resid");  
            //实战中如果图片耗时应该令其一个线程去拉图片异步,不然把UI线程卡死.  
//            mAlbumImageView.setImageResource(resId);  
            setData(mObject);
//        }catch (JSONException e) {  
//            e.printStackTrace();  
//        }  
    }
//    public void loadDisscussTask(boolean isInited){
//    	if (isInited) {
//			return;
//		}else
//		{
//			loadDisscussTask();
//		}
//    }
    private boolean loading = false;
   
    private OnClickListener ButtonOnclickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
				( (PhotoFrameActivity)mContext ).stopOrContinue(
						! ((PhotoFrameActivity)mContext ).play_stop );
				
		}
	};
	
	
	private OnTouchListener ontouchlistener = new OnTouchListener() {
		
		float mLastY = 0;
		float mCurrentY = 0;
		float mMoveY = 0;
		AudioManager audioManager;
		boolean flag = false;
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				mLastY = mMoveY = event.getY();
				flag = false;
				break;
			case MotionEvent.ACTION_UP:
				mCurrentY = event.getY();
				if (audioManager == null) {
					audioManager = (AudioManager) mContext.getSystemService(
							Context.AUDIO_SERVICE);
				}
				if (Math.abs(mLastY - mCurrentY) <= 5 && !flag) {
					( (PhotoFrameActivity)mContext ).stopOrContinue(
							! ((PhotoFrameActivity)mContext ).play_stop );
				}
				break;
			case MotionEvent.ACTION_MOVE:
				//float moveY = event.getY();
				if (audioManager == null) {
					audioManager = (AudioManager) mContext.getSystemService(
							Context.AUDIO_SERVICE);
				}
				mCurrentY = event.getY();
				if (mCurrentY > mMoveY && mCurrentY - mMoveY > 20) {
					if (SoundPlayStop.mediaPlayer != null && SoundPlayStop.mediaPlayer.isPlaying()) {
						audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
								AudioManager.ADJUST_LOWER, 0);
						if (PhotoFrameActivity.mLevelRl.getVisibility() == View.INVISIBLE) {
							PhotoFrameActivity.mLevelRl.setVisibility(View.VISIBLE);
						}
						int soundlevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
						if (soundlevel < 13) {
							PhotoFrameActivity.mLevelTv.setBackgroundResource(levelId[soundlevel / 2 + soundlevel % 2]);
						} else {
							PhotoFrameActivity.mLevelTv.setBackgroundResource(levelId[soundlevel - 6]);
						}
						count = 0;
						if (mFlag) {
							mFlag = false;
							executorService.submit(new Runnable() {
								
								@Override
								public void run() {
									count = 0;
									while(count < 2) {
										try {
											Thread.sleep(1000);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										count ++ ;
									}
									handler.sendEmptyMessage(0);
									
								}
							});
						}
						
					}
					if (!flag && mCurrentY - mMoveY > 5) {
						flag = true;
					}
					mMoveY = mCurrentY;
				}else if (mCurrentY < mMoveY && mCurrentY - mMoveY < -20) {
					if (SoundPlayStop.mediaPlayer != null && SoundPlayStop.mediaPlayer.isPlaying()) {
						audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, 
								AudioManager.ADJUST_RAISE, 0);
						if (PhotoFrameActivity.mLevelRl.getVisibility() == View.INVISIBLE) {
							PhotoFrameActivity.mLevelRl.setVisibility(View.VISIBLE);
						}
						int soundlevel = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
						if (soundlevel < 13) {
							PhotoFrameActivity.mLevelTv.setBackgroundResource(levelId[soundlevel / 2 + soundlevel % 2]);
						} else {
							PhotoFrameActivity.mLevelTv.setBackgroundResource(levelId[soundlevel - 6]);
						}
						count = 0;
						if (mFlag) {
							mFlag = false;
							executorService.submit(new Runnable() {
								
								@Override
								public void run() {
									count = 0;
									while(count < 2) {
										try {
											Thread.sleep(1000);
										} catch (InterruptedException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										count ++ ;
									}
									handler.sendEmptyMessage(0);
									
								}
							});
						}
						
					}
					if (!flag && mCurrentY - mMoveY < -5) {
						flag = true;
					}
					mMoveY = mCurrentY;
				}
				break;
			default:
				break;
			}
			return true;
		}
	};
	
	@Override
	public boolean isLoadDisscussed() {
		// TODO Auto-generated method stub
		return loading;
	}
	@Override
	public void loadDisscussTask() {
		// TODO Auto-generated method stub
		
	}
	
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if (PhotoFrameActivity.mLevelRl.getVisibility() == View.VISIBLE) {
					PhotoFrameActivity.mLevelRl.setVisibility(View.INVISIBLE);
				}
				mFlag = true;
				break;

			default:
				break;
			}
		}
	};
	private int count = 0;
	private boolean mFlag = true;
	private ExecutorService executorService = Executors.newFixedThreadPool(5);
	
}
